<template>
  <n-space class="page" vertical>
    <n-space justify="space-between">
      <n-button @click="createPage"> 新建页面 </n-button>
      <n-form
        ref="formRef"
        inline
        :label-width="80"
        :model="formValue"
        label-placement="left"
        :rules="rules"
      >
        <n-form-item label="名称" path="name">
          <n-input v-model:value="formValue.name" />
        </n-form-item>
        <n-form-item label="路径" path="path">
          <n-input v-model:value="formValue.path" />
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-select
            v-model:value="formValue.status"
            clearable
            :options="statusOptions"
          />
        </n-form-item>
        <n-form-item>
          <n-button @click="findClick"> 查询 </n-button>
        </n-form-item>
      </n-form>
    </n-space>
    <n-data-table
      :columns="columns"
      :data="data"
      :pagination="pagination"
      :bordered="false"
      remote
      :row-key="rowKey"
      @update:page-size="handlePageSizeChange"
      @update:page="handlePageChange"
    />
  </n-space>
</template>

<script setup lang="ts">
import {
  type FormInst,
  type FormItemRule,
  NForm,
  NFormItem,
  NInput,
  NButton,
  NSelect,
  NSpace,
  NDataTable,
  NTag,
  type SelectOption,
  type SelectGroupOption,
  type DataTableColumns,
} from "naive-ui";
import {
  StatusContent,
  statusOptions,
  findAll as apiPageFindAll,
  updateOne as apiPageUpdate,
  deletePage as apiPageDelete,
  type page,
} from "~/api/page";
useHead({
  title: "页面管理", //网站标题
});

definePageMeta({
  title: "页面管理",
});

const createPage = async () => {
  await navigateTo("/page/writePage");
};

const formRef = ref<FormInst | null>();
const formValue = ref({
  name: "",
  path: "",
  status: null,
});
const rules = {
  name: {
    pattern: /^.{0,10}$/,
    message: "查询长度小于10",
    trigger: "input",
  },
  path: {
    pattern: /^.{0,10}$/,
    message: "查询长度小于10",
    trigger: "input",
  },
};

const findClick = (e: MouseEvent) => {
  e.preventDefault();
  const messageReactive = naiveui.message.loading("Verifying", {
    duration: 0,
  });
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      findPageList();
    } else {
      naiveui.message.error(errors[0][0].message ?? "表单验证错误");
    }
    messageReactive.destroy();
  });
};

const dayjs = useDayjs();
const createColumns = ({
  edit,
  del,
  updateStatus,
}: {
  edit: (row: page) => void;
  del: (row: page) => void;
  updateStatus: (row: page) => void;
}): DataTableColumns<page> => {
  return [
    {
      title: "页面名",
      key: "name",
    },
    {
      title: "路径地址",
      key: "path",
    },
    {
      title: "开启评论区",
      key: "isCommentOpen",
      render(row: page) {
        return h(
          NTag,
          {
            type: row.isCommentOpen ? "success" : "info",
            bordered: false,
          },
          {
            default: () => (row.isCommentOpen ? "评论开启" : "评论关闭"),
          }
        );
      },
    },
    {
      title: "状态",
      key: "status",
      render(row: page) {
        return h(
          NTag,
          {
            type: row.status === StatusContent.Publish ? "success" : "info",
            bordered: false,
          },
          {
            default: () => row.status,
          }
        );
      },
    },
    {
      title: "排序",
      key: "order",
    },
    {
      title: "访问量",
      key: "views",
    },
    {
      title: "发布时间",
      key: "publishTime",
      render(row: page) {
        return dayjs(row.publishTime).format("YYYY年MM月DD日");
      },
    },
    {
      title: "Action",
      key: "actions",
      render(row: page) {
        const editAction = h(
          NButton,
          {
            strong: true,
            tertiary: true,
            size: "small",
            style: {
              margin: "0px 5px",
            },
            onClick: () => edit(row),
          },
          { default: () => "编辑" }
        );
        const delAction = h(
          NButton,
          {
            strong: true,
            tertiary: true,
            size: "small",
            style: {
              margin: "0px 5px",
            },
            onClick: () => del(row),
          },
          { default: () => "删除" }
        );
        const updateStatusActions = h(
          NButton,
          {
            strong: true,
            tertiary: true,
            size: "small",
            style: {
              margin: "0px 5px",
            },
            onClick: () => updateStatus(row),
          },
          {
            default: () =>
              row.status === StatusContent.Publish ? "下线" : "上线",
          }
        );
        return [editAction, delAction, updateStatusActions];
      },
    },
  ];
};

const data = ref<page[]>([]);

const columns = createColumns({
  async edit(row: page) {
    await navigateTo({
      path: "/page/writePage",
      query: { id: row.id },
    });
  },
  async del(row: page) {
    await apiPageDelete(row.id);
    findPageList();
  },
  async updateStatus(row: page) {
    await apiPageUpdate(row.id, {
      status:
        row.status === StatusContent.Publish
          ? StatusContent.Draft
          : StatusContent.Publish,
    });
    findPageList();
  },
});
const rowKey = (rowData: { id: any }) => {
  return rowData.id;
};
const handlePageChange = (page: number) => {
  pagination.value.page = page;
  findPageList();
};
const handlePageSizeChange = (pageSize: number) => {
  pagination.value.pageSize = pageSize;
  pagination.value.page = 1;
  findPageList();
};
const pagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  pageSizes: [3, 5, 7],
});
const findPageList = async () => {
  const res = await apiPageFindAll({
    ...formValue.value,
    pageNum: pagination.value.page,
    pageSize: pagination.value.pageSize,
  });
  if (res.data) {
    data.value = res.data.list;
    pagination.value.itemCount = res.data.count;
  }
};
onMounted(async () => {
  findPageList();
});
</script>
<style lang="scss" scoped>
.page {
  padding: 20px 15px;
  .n-input,
  .n-select {
    width: 200px;
  }
  .n-pagination {
    justify-content: center;
  }
}
</style>
